import { action, makeObservable, observable } from 'mobx'
import { fetchLogin, fetchUserInfo, getTemplate, deleteTemplate, downloadTemplate, updateTemplate } from '@/api/user'
import { setToken } from '@/utils/auth'
import { StoreKey } from '@/common/constants'
import { useStorage } from '@/hooks/common'

class User {
  constructor() {
    makeObservable(this)
  }

  @observable menus = []
  @action login = async (data: any) => {
    try {
      const storage = useStorage()
      let response: any = await fetchLogin(data)
      const { access_token, authority_type } = response
      switch (authority_type) {
        case "admin":
          response.nickname = "管理员"
          break;
        case "hr":
          response.nickname = "人事"
          break;
        default:
          response.nickname = "财务"
          break;
      }
      delete response['access_token']
      setToken(access_token)
      storage.set({ path: 'info', value: response })
      return Promise.resolve(response)
    } catch (e) {
      return Promise.reject(e)
    }
  }
  // @action login = async (data: any) => {
  //   try {
  //     const response: any = await fetchLogin(data)
  //     const { token } = response

  //     setToken(token)

  //     return Promise.resolve(response)
  //   } catch (e) {
  //     return Promise.reject(e)
  //   }
  // }

  @action getInfo = async (data?: any) => {
    try {
      const storage = useStorage()
      const user: any = await fetchUserInfo(data)

      storage.set({ path: 'info', value: user })

      return Promise.resolve(user)
    } catch (e) {
      return Promise.reject(e)
    }
  }

  @action logout = () => {
    localStorage.removeItem(StoreKey)
  }


  @action getTemplate = async (data?: any) => {
    try {
      const value: any = await getTemplate(data)
      return Promise.resolve(value)
    } catch (e) {
      return Promise.reject(e)
    }
  }

  @action deleteTemplate = async (data?: any) => {
    try {
      const value: any = await deleteTemplate(data)
      return Promise.resolve(value)
    } catch (e) {
      return Promise.reject(e)
    }
  }
  @action downloadTemplate = async (data?: any) => {
    try {
      const value: any = await downloadTemplate(data)
      return Promise.resolve(value)
    } catch (e) {
      return Promise.reject(e)
    }
  }
  // 
  @action updateTemplate = async (data?: any) => {
    try {
      const value: any = await updateTemplate(data)
      return Promise.resolve(value)
    } catch (e) {
      return Promise.reject(e)
    }
  }

}

export default new User()
